<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48" @keyup.enter.native="searchList">
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="经销商">
                <a-select
                  show-search
                  label-in-value
                  allowClear
                  v-model="queryParam.cstoreId"
                  placeholder="请输入搜索词"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="fetching ? undefined : null"
                  @search="fetchUser"
                  @change="handleChange"
                  :getPopupContainer="triggerNode => triggerNode.parentNode"
                >
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="d in storeList" :key="d.cstoreId">
                    {{ d.cstoreName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="选择日期">
                <a-range-picker
                  style="width: 100%"
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryParam.timePicker"
                />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24" v-if="queryParam.type == 1">
              <a-form-item label="提交状态">
                <a-select v-model="queryParam.submitStatus" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="0">未提交</a-select-option>
                  <a-select-option :value="1">已提交</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="12" :lg="8" :md="24" :sm="24" v-if="queryParam.type != 1">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 8px" @click="handleImport" v-if="queryParam.type == 0" v-has="'dealerReconciliation:import'">导入</a-button>
              </span>
            </a-col>
            <a-col :xxl="6" :lg="24" :md="24" :sm="24" v-if="queryParam.type == 1">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 8px" @click="handleSubmitDebit('all')" v-has="'dealerReconciliation:submitAll'">全部提交</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs :activeKey="queryParam.type" @change="tabsChange">
        <a-tab-pane :key="0" tab="未结算"></a-tab-pane>
        <a-tab-pane :key="1" tab="待结算"></a-tab-pane>
        <a-tab-pane :key="2" tab="已结算"></a-tab-pane>
      </a-tabs>
      <s-table
        ref="table"
        size="default"
        :rowKey="record => record.billNo"
        :columns="queryParam.type == 0 ? columns : queryParam.type == 1 ? columnsPre : columnsSettle"
        :data="loadData"
        :pagination="paginationProps"
        :scroll="{ x: queryParam.type == 1 ? 1700 : queryParam.type == 2 ? 1900 : null }"
      >
        <span slot="action" slot-scope="text, record">
          <template v-if="record.submitStatus == 0">
            <a @click="handleEdit(record)" v-has="'dealerReconciliation:editFreight'">修改运费</a>
            <a-popconfirm title="确定提交扣款吗?" ok-text="Yes" cancel-text="No" @confirm="handleSubmitDebit(record)" style="margin-left: 8px" v-has="'dealerReconciliation:submit'">
              <a href="#">提交扣款</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>
    </a-card>
    <a-modal :visible="visible" :destroyOnClose="true" title="导入" :footer="null" :maskClosable="false" @cancel="handleClose" width="600px">
      <a-steps :current="current" size="small" style="margin-bottom:24px">
        <a-step v-for="(item, index) in steps" :key="index" :title="item.title" />
      </a-steps>
      <a-form-model ref="ruleForm" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" style="margin-bottom:48px">
        <template v-if="current == 0">
          <a-form-model-item>
            <a-select v-model="form.type" placeholder="请选择快递公司">
              <a-select-option :value="item.type" v-for="item in expressList" :key="item.type">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <p class="tip" v-if="showName">请选择快递公司</p>
          </a-form-model-item>
        </template>
        <template v-if="current == 1">
          <a-button type="primary" @click="handleImportXls">导入</a-button>
          <j-import-modal ref="importModal" :uploadParams="getUploadParams()" @ok="importOk" :serviceId="8" :fileSize="10" :outId="form.type + ',' + Userinfo.realname"></j-import-modal>
        </template>
      </a-form-model>
      <div class="steps-action">
        <a-button v-if="current < steps.length - 1" type="primary" @click="next">
          下一步
        </a-button>
        <a-button v-if="current == steps.length - 1" type="primary" :disabled="true">
          完成
        </a-button>
        <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
          上一步
        </a-button>
      </div>
    </a-modal>
    <a-modal :visible="visibleFreight" :destroyOnClose="true" title="导入" :maskClosable="false" @ok="handelOk" @cancel="visibleFreight = false">
      <div class="freight">运费:<a-input-number :min="0" :step="0.01" v-model="freight" placeholder="" /></div>
    </a-modal>
  </div>
</template>
<script>
import { listMixin } from '@/views/box/util/listMixin'
import moment from 'moment'
import 'moment/locale/zh-cn'
import debounce from 'lodash/debounce'
import globalData from '@/assets/js/common'
import { queryUploadSuccess } from '@/components/qiniuUpload/common'
import JImportModal from '@/components/qiniuUpload/JImportModal'
import { querySettle, queryCStore, queryExpressType, submitDebitNote, updateFreight } from '@/api/box/marketing'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
let columns = [
  { align: 'center', dataIndex: 'billNo', title: '运单号' },
  { title: '订单号', dataIndex: 'expressOrderId', align: 'center' },
  { title: '业务单号', dataIndex: 'boxSn', align: 'center' },
  { title: '经销商', dataIndex: 'cstoreName', align: 'center' },
  { title: '经销商门店', dataIndex: 'storeName', align: 'center' },
  { title: '运单单据时间', dataIndex: 'wayBillTime', align: 'center' }
]
let columnsPre = [
  { title: '运单号', dataIndex: 'billNo', align: 'center' },
  { title: '订单号', dataIndex: 'expressOrderId', align: 'center' },
  { title: '业务单号', dataIndex: 'boxSn', align: 'center' },
  { title: '运费', dataIndex: 'freight', align: 'center', width: 100 },
  { title: '经销商', dataIndex: 'cstoreName', align: 'center' },
  { title: '运单单据时间', dataIndex: 'wayBillTime', align: 'center' },
  { title: '申请时间', dataIndex: 'applyTime', align: 'center' },
  { title: '申请人', dataIndex: 'applyPerson', align: 'center', width: 120 },
  { title: '状态', dataIndex: 'submitStatus', align: 'center', customRender: text => (text == 1 ? '已提交' : '未提交') },
  { title: '操作', align: 'center', fixed: 'right', scopedSlots: { customRender: 'action' }, width: 160 }
]
let columnsSettle = [
  { align: 'center', dataIndex: 'billNo', title: '运单号' },
  { title: '订单号', dataIndex: 'expressOrderId', align: 'center' },
  { title: '业务单号', dataIndex: 'boxSn', align: 'center' },
  { title: '运费', dataIndex: 'freight', align: 'center', width: 100 },
  { title: '经销商', dataIndex: 'cstoreName', align: 'center' },
  { title: '经销商门店', dataIndex: 'storeName', align: 'center' },
  { title: '运单单据时间', dataIndex: 'wayBillTime', align: 'center' },
  { title: '扣款单号  ', dataIndex: 'distributesOrder', align: 'center' },
  { title: '申请时间', dataIndex: 'applyTime', align: 'center' },
  { title: '申请人', dataIndex: 'applyPerson', align: 'center', width: 120 },
  { title: '提交扣款时间', dataIndex: 'submitTime', align: 'center' },
  { title: '提交人  ', dataIndex: 'submitPerson', align: 'center', width: 120 }
]
export default {
  mixins: [listMixin],
  components: { JImportModal },
  data() {
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      columns,
      columnsPre,
      columnsSettle,
      queryParam: {
        cstoreId: undefined,
        type: 0,
        timePicker: null,
        submitStatus: ''
      },
      storeList: [],
      fetching: false,
      visible: false,
      form: {},
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      expressList: [],
      current: 0,
      steps: [
        {
          title: '选择快递公司'
        },
        {
          title: '导入'
        }
      ],
      timer: null,
      showName: false,
      visibleFreight: false,
      freight: '',
      freightId: '',
      Userinfo: Vue.ls.get(USER_INFO)
    }
  },
  computed: {
    loadData() {
      return parameter => {
        return this.fetchData(parameter)
      }
    }
  },
  mounted() {
    this.uploadParams = { ...globalData.uploadParams }
    this.uploadHost = this.uploadParams.uploadHost
    this.getExpress()
  },
  methods: {
    moment,
    tabsChange(key) {
      if (key != 1) {
        this.queryParam.submitStatus = ''
      }
      this.queryParam.type = key
      this.$refs.table.refresh(true)
    },
    handleSearch(value) {
      // console.log(value)
      this.getCStore(value, data => (this.storeList = data))
    },
    handleChange(value) {
      // console.log('handleChange', value)
      this.queryParam.cstoreId = value
      this.storeList = []
      this.fetching = false
    },
    fetchUser(value) {
      console.log('fetching user', value)
      this.fetching = true

      let params = {
        requestData: {
          cstoreName: value
        }
      }
      queryCStore(params).then(res => {
        if (res.code == 0) {
          this.storeList = res.data.splice(0, 20)
        } else {
          this.$message.warning(res.msg)
          this.storeList = []
        }
        this.fetching = false
      })
    },
    resetList() {
      this.queryParam.cstoreId = undefined
      this.queryParam.timePicker = null
      this.queryParam.submitStatus = ''
      this.$refs.table.refresh(true)
    },
    getExpress() {
      queryExpressType().then(res => {
        if (res.code == 0) {
          this.expressList = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fetchData(parameter) {
      let formValue = this.filterFields(this.queryParam)
      try {
        let params = {
          page: parameter,
          requestData: formValue
        }
        return this.fetchList(params, querySettle).then(res => {
          if (res.code == 0) {
            return {
              data: res.data,
              page: res.page
            }
          } else {
            this.$message.warning(res.msg)
            return {
              data: [],
              page: {
                pageNo: 1,
                pageSize: 10,
                count: 0
              }
            }
          }
        })
      } catch (err) {
        console.log(err)
      }
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined && values[i] !== null) {
          if (i == 'timePicker') {
            formValue.startTime = values[i][0].format('YYYY-MM-DD HH:mm:ss')
            formValue.endTime = values[i][1].format('YYYY-MM-DD HH:mm:ss')
          } else if (i == 'cstoreId') {
            formValue.cstoreId = values[i].key
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    handleImport() {
      this.visible = true
    },
    // 导入
    handleImportXls() {
      this.$refs.importModal.show()
    },
    getUploadParams() {
      // console.log({...globalData.uploadParams})
      return { ...globalData.uploadParams }
    },
    // 上传成功后的方法
    importOk(result, fileList) {
      let that = this
      queryUploadSuccess(this.timer, result, 60000, function(x, data) {
        console.log(x, data)
        if (x == 'done' || x == 'warning') {
          that.$refs.importModal.close()
        }
        if (x == 'done') {
          if (!data.url) {
            // that.$message.success('导入成功！')
          }
          that.handleClose()
          that.$refs.table.refresh(true)
        }
      })
    },
    // 提交扣款
    handleSubmitDebit(record) {
      let params = null
      if (record != 'all') {
        params = {
          requestData: {
            id: record.id,
            all: 0
          }
        }
        this.comSubmitDebitNote(params, record)
      } else {
        let self = this
        this.$confirm({
          title: '确认全部提交？',
          content: h => <div style="color:red;"></div>,
          onOk() {
            params = {
              requestData: {
                all: 1
              }
            }
            self.comSubmitDebitNote(params, record)
          },
          onCancel() {},
          class: 'test'
        })
      }
    },
    comSubmitDebitNote(params, record) {
      submitDebitNote(params).then(res => {
        if (res.code == 0) {
          if (record != 'all') {
            this.$refs.table.refresh()
          } else {
            this.$refs.table.refresh(true)
          }
          this.$message.success('提交成功')
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 编辑运费
    handleEdit(record) {
      this.visibleFreight = true
      this.freight = record.freight
      this.freightId = record.id
    },
    handelOk() {
      if (this.freight) {
      } else {
        this.$message.warning('请输入运费！')
        return
      }
      let params = {
        requestData: {
          freight: this.freight.toFixed(2),
          id: this.freightId
        }
      }
      updateFreight(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功！')
          this.visibleFreight = false
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleClose() {
      this.visible = false
      this.form = {}
      this.current = 0
    },
    next() {
      if (!this.form.type) {
        this.showName = true
      } else {
        this.showName = false
        this.current++
      }
    },
    prev() {
      this.current--
    }
  }
}
</script>
<style lang="less" scoped>
.tip {
  color: #f5222c;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: -1px;
}
.freight {
  display: flex;
  align-items: center;
  /deep/.ant-input-number {
    margin-left: 8px;
  }
}
</style>

